/**
 * Copyright(c) Hainan eKing Technology co., LTD
 *
 * @date 2013年8月13日
 * 	
 * Original Author: 郑兴(zhengxing)
 *
 * ChangeLog
 *
 */
package com.hnas.sys.web.system;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hnas.core.dto.BaseAjaxResponse;
import com.hnas.core.dto.DTOPagedList;
import com.hnas.core.dto.DataBean;
import com.hnas.sys.core.util.CacheUtil;
import com.hnas.sys.core.util.UserUtils;
import com.hnas.sys.domain.ResourceStatus;
import com.hnas.sys.service.system.AuthorityService;
import com.hnas.sys.service.system.ResourceService;
import com.hnas.sys.service.system.UserAuthorityService;
import com.hnas.sys.service.system.UserService;
import com.hnas.sys.service.system.criteria.DTOSearchAuthority;
import com.hnas.sys.service.system.data.DTOPackage;
import com.hnas.sys.service.system.dto.DTOAuthority;
import com.hnas.sys.service.system.dto.DTOUser;

/**
 * <pre>期权管理控制器</pre>
 * @author 郑兴(zhengxing)
 *
 */
@Controller
@RequestMapping("/backend/system/authority")
public class AuthorityController {
	@Autowired
	AuthorityService authorityService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private ResourceService resourceService;
	private Logger log = LoggerFactory.getLogger(AuthorityController.class);
	/**
	 * <pre>显示权限列表</pre>
	 * @Auther 郑兴(zhengxing)
	 * @date 2013年8月28日 下午9:42:44
	 * @param map
	 * @return
	 */
//	@RequestMapping("/list")
//	public String searchAuthorities(ModelMap modelMap, HttpServletRequest request,
//			@ModelAttribute("criteria") DTOSearchAuthority criteria) {
////		map.put("authorities", loadAuthority(false));
////		return "/backend/system/authority";
//		this.search(modelMap, request, criteria);
//		modelMap.put("resources", this.resourceService.loadAllResource());		
//		return "backend/system/authority/listAuthority2";
//	}
	
	@RequestMapping("/search")
	public String search(ModelMap modelMap, HttpServletRequest request,
			@ModelAttribute("criteria") DTOSearchAuthority criteria) {

		try {
//			String page = request.getParameter((new ParamEncoder("values")
//					.encodeParameterName(TableTagParameters.PARAMETER_PAGE)));
//			/**
//			 * if (!"false".equals(request.getParameter("firstInvoke"))) {
//			 * modelMap.put("resultSize", 0); return
//			 * "backend/product/searchProviders"; }
//			 **/
//			if (null == page) {
//				criteria.setPageNo(1);
//			} else {
//				criteria.setPageNo(Integer.parseInt(page));
//			}
			criteria.setTotalCount(-1);
			DTOUser user = UserUtils.getCurrentUser();

			DTOPagedList<DTOAuthority> pg = this.authorityService.search(criteria);
//			modelMap.put("citys", pg.getList());
			modelMap.put("pg", pg);
			modelMap.put("resultSize", pg.getTotalCount());
			modelMap.put("dto", criteria);
		} catch (Exception e) {
			log.error("", e);
			modelMap.put("resultSize", 0);
		}
		modelMap.put("pageTitle", "角色维护");
		List<DataBean> beans = new ArrayList<DataBean>();
		beans.add(new DataBean("name","名称"));
		beans.add(new DataBean("description","描述"));
//		beans.add(new DataBean("statusStr","状态"));
//		beans.add(new DataBean("priority","排序","int"));
		modelMap.put("beans", beans);
		return "backend/system/authority/listAuthority";
	}
	@RequestMapping("/showPage")
	public String showPage(ModelMap modelMap, Long id) {
		
//		try {
		DTOAuthority dto = null;
			if(null==id || id==0){
				dto = new DTOAuthority();
			}else{
				dto = this.authorityService.load(id);
			}
			//加载权限
			//默认选中
			
//		modelMap.put("pageTitle", "角色维护");
//		List<DataBean> beans = new ArrayList<DataBean>();
//		beans.add(new DataBean("name","名称"));
//		beans.add(new DataBean("description","描述"));
//		beans.add(new DataBean("statusStr","状态"));
//		beans.add(new DataBean("priority","排序","int"));
			List<DTOPackage> packages = this.authorityService.getAuthorityForDisplay(id);
			modelMap.put("rows", packages);
		modelMap.put("dto", dto);
		return "backend/system/authority/showPage";
	}
	
	/**
	 * <pre>加载所有权限</pre>
	 * @Auther 郑兴(zhengxing)
	 * @param map
	 * @return
	 */
//	@RequestMapping("/ajax")
//	@ResponseBody
//	public List<DTOAuthority> ajaxSearchAuthorities(ModelMap map) {
//		return loadAuthority(false);
//	}
	
	/**
	 * <pre>加载权限信息，默认从缓存加载，缓存无数据则从数据库加载</pre>
	 * @Auther 郑兴(zhengxing)
	 * @return
	 */
	private List<DTOAuthority> loadAuthority(boolean updateCache) {
		/*从数据库加载所有权限信息*/
		if(updateCache || CollectionUtils.isEmpty(CacheUtil.getAuthorityCache())) {
			List<DTOAuthority> authorities = authorityService.loadAll();
			CacheUtil.setAuthorityCache(authorities);
			return authorities;
		}
		/*从缓存加载资源*/
		return CacheUtil.getAuthorityCache();
	}
	
	/**
	 * <pre>加载权限对象</pre>
	 * @Auther 郑兴(zhengxing)
	 * @date 2013年8月28日 下午11:39:12
	 * @param map
	 * @return
	 */
	@RequestMapping(value="show/{id}", method = RequestMethod.POST)
	@ResponseBody
	public DTOAuthority loadAuthority(@PathVariable("id")Long id) {
		return authorityService.load(id);
	}
	
	/**
	 * <pre>添加或更新权限</pre>
	 * @Auther 郑兴(zhengxing)
	 * @date 2013年8月28日 下午9:47:28
	 * @param authority
	 * @return
	 */
	@RequestMapping(value="/savePage", method = RequestMethod.POST)
	@ResponseBody
	public BaseAjaxResponse savePage(@ModelAttribute("authority")DTOAuthority authority) {
		BaseAjaxResponse res = new BaseAjaxResponse();
		DTOAuthority dtoAuthority = this.authorityService.loadAuthorityByName(authority.getName());
		if(null!=dtoAuthority && dtoAuthority.getId() != authority.getId()){
			res.setResult(0);
			res.setErrorMessage("权限名称已存在!");
			return res;
		}
		try {
			this.authorityService.saveOrUpdate(authority,true);
			res.setResult(1);
		} catch (Exception e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
			res.setErrorMessage(e.getMessage());
		}		
		return res;
	}
	
	/**
	 * <pre>启用或禁用权限</pre>
	 * @Auther 郑兴(zhengxing)
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/toggle/{id}", method = RequestMethod.POST)
	@ResponseBody
	public BaseAjaxResponse toggleStatus(@PathVariable("id")Long id) {
		BaseAjaxResponse response = new BaseAjaxResponse();
		try {
			DTOAuthority authority = authorityService.load(id);
			List<DTOUser> dtoUser=this.userService.getUsersWithRole(authority.getName());
			if(null!=dtoUser&&dtoUser.size()>0){
				response.setErrorMessage("已经分配权限,不能删除");
				response.setResult(BaseAjaxResponse.FAIL);
			}else{
				if(authority.getStatus() == ResourceStatus.INVALID) {
//					authority.setStatus(ResourceStatus.VALID);
					this.authorityService.saveOrUpdate(authority, false);
				} else {
//					authority.setStatus(ResourceStatus.INVALID);
					this.authorityService.disable(id);
				}
				response.setResult(BaseAjaxResponse.SUCCESS);
			}
			
//			authorityService.saveOrUpdate(authority);
//			CacheUtil.setAuthorityCache(authorityService.loadAll());
			
		} catch (Exception e) {
			response.setErrorMessage(e.getMessage());
		}
		return response;
	}
	
	@RequestMapping(value = "disable/{id}", method = RequestMethod.POST)
	@ResponseBody
	public BaseAjaxResponse disable(@PathVariable("id") Long id) {
		BaseAjaxResponse res = new BaseAjaxResponse();
		DTOAuthority authority = authorityService.load(id);
		List<DTOUser> dtoUser=this.userService.getUsersWithRole(authority.getName());
		if(null!=dtoUser&&dtoUser.size()>0){
			res.setErrorMessage("已经分配权限,不能删除");
			res.setResult(-1);
		}else{
			this.authorityService.disable(id);
			res.setResult(1);
		}
		
		return res;
	}
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public BaseAjaxResponse add( DTOAuthority dto) {
		return this.save(dto);
	}
	@RequestMapping(value = "save", method = RequestMethod.POST)
	@ResponseBody
	public BaseAjaxResponse save( DTOAuthority dto) {
		BaseAjaxResponse res = new BaseAjaxResponse();
		try {
			this.authorityService.saveOrUpdate(dto,false);
			res.setResult(1);
		} catch (Exception e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
			res.setErrorMessage(e.getMessage());
		}		
		return res;
	}
}
